//
//  MusicScrollView.m
//  QQMusic
//
//  Created by wwj on 16/4/25.
//  Copyright © 2016年 wwj. All rights reserved.
//

#import "MusicScrollView.h"
#import "MusicViewCell.h"
#import "Masonry.h"
#import "LrcTool.h"
#import "XMGLrcline.h"
#import "LrcLable.h"
#import "XMGMusic.h"
#import "MusicTool.h"
#import <MediaPlayer/MediaPlayer.h>

@interface MusicScrollView ()<UITableViewDataSource>
@property (weak, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSArray *lrcArray;
@property (assign, nonatomic) NSInteger nowIndex;
@end

@implementation MusicScrollView
static CGFloat const SSize = 17;
static CGFloat const BSize = 22;


static NSString *const ID = @"cell";

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self initView];
    }
    return self;
}

- (NSArray *)lrcArray{
    if (_lrcArray == nil) {
        _lrcArray = [NSArray array];
    }
    return _lrcArray;
}

- (instancetype)initWithCoder:(NSCoder *)coder{
    self = [super initWithCoder:coder];
    if (self) {
        [self initView];
    }
    return self;
}

- (void)initView{
    UITableView *tableView = [[UITableView alloc] init];
    tableView.translatesAutoresizingMaskIntoConstraints = NO;
    tableView.contentInset = UIEdgeInsetsMake(self.bounds.size.height * 0.5, 0, self.bounds.size.height * 0.5, 0);
    [tableView registerClass:[MusicViewCell class] forCellReuseIdentifier:ID];
    tableView.dataSource = self;
    
    [self addSubview:tableView];
    self.tableView = tableView;
    

    
}

- (void)layoutSubviews{
    [super layoutSubviews];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left).offset(self.bounds.size.width);
        make.right.equalTo(self.mas_right);
        make.top.equalTo(self.mas_top);
        make.bottom.equalTo(self.mas_bottom);
        make.width.equalTo(self.mas_width);
        make.height.equalTo(self.mas_height);
    }];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)setMusicName:(NSString *)musicName{
    self.nowIndex = 0;
    _musicName = [musicName copy];
    self.lrcArray = [LrcTool lrcsWithName:musicName];
    [self.tableView reloadData];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.lrcArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MusicViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    XMGLrcline *lrcModel = self.lrcArray[indexPath.row];
    cell.lrcLable.text = lrcModel.text;
    if (indexPath.row == self.nowIndex) {
        cell.lrcLable.font = [UIFont systemFontOfSize:BSize];
    }else{
        cell.lrcLable.font = [UIFont systemFontOfSize:SSize];
        cell.lrcLable.time = 0.0;
    }
    return cell;
}

- (void)setTime:(NSTimeInterval)time{
    NSInteger count = self.lrcArray.count;
    for (NSInteger index = 0; index < count; index++) {
        
        NSInteger nextIndex = index + 1;
        if (nextIndex >= self.lrcArray.count) return;
        XMGLrcline *nowLrc = self.lrcArray[index];
        XMGLrcline *nextLrc = self.lrcArray[nextIndex];
        
        if (time >= nowLrc.time && time < nextLrc.time && self.nowIndex != index) {
            NSIndexPath *nowIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
            NSIndexPath *perIndexPath = [NSIndexPath indexPathForRow:self.nowIndex inSection:0];
            NSLog(@"%zd", self.nowIndex);
            self.nowIndex = index;
            [self.tableView reloadRowsAtIndexPaths:@[nowIndexPath, perIndexPath] withRowAnimation:UITableViewRowAnimationNone];
            [self.tableView scrollToRowAtIndexPath:nowIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
            
            self.lrcLable.text = nowLrc.text;
            [self settingBack];
        }
        
        if (self.nowIndex == index){
            NSIndexPath *nowIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
            MusicViewCell *cell = (MusicViewCell *)[self.tableView cellForRowAtIndexPath:nowIndexPath];
            cell.lrcLable.time = (time - nowLrc.time) / (nextLrc.time - time);
            self.lrcLable.time = (time - nowLrc.time) / (nextLrc.time - time);
            NSLog(@"currentTime:%f, lrcTime:%f", time, cell.lrcLable.time);
        }
    }
}

- (void)settingBack{
    XMGMusic *music = [MusicTool currentMusic];
    NSString *perLrc,*nowLrc, *nextLrc;
    nowLrc = [self.lrcArray[self.nowIndex] text];
    NSInteger perIndex = self.nowIndex - 1;
    NSInteger nextIndex = self.nowIndex + 1;
    if (perIndex >= 0) {
        perLrc = [self.lrcArray[perIndex] text];
    }
    if (nextIndex < self.lrcArray.count) {
        nextLrc = [self.lrcArray[nextIndex] text];
    }
    UIImage *image = [UIImage imageNamed:music.icon];
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0);
    
    CGFloat lrcH = 25.0;
    CGFloat width = image.size.width;
    CGFloat height = image.size.height;
    
    [image drawInRect:CGRectMake(0, 0, width, height)];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.alignment = NSTextAlignmentCenter;
    NSDictionary *dictA = @{
        NSFontAttributeName :[UIFont systemFontOfSize:SSize],
        NSForegroundColorAttributeName : [UIColor lightTextColor],
        NSParagraphStyleAttributeName : style
    };
    NSDictionary *dictB = @{
        NSFontAttributeName :[UIFont systemFontOfSize:20],
        NSForegroundColorAttributeName : [UIColor whiteColor],
        NSParagraphStyleAttributeName : style
    };
    [perLrc drawInRect:CGRectMake(0, height - 3 * lrcH, width, height) withAttributes:dictA];
    [nowLrc drawInRect:CGRectMake(0, height - 2 * lrcH, width, height) withAttributes:dictB];
    [nextLrc drawInRect:CGRectMake(0, height - lrcH, width, height) withAttributes:dictA];
    NSLog(@"%@, %@, %@", perLrc, nowLrc, nextLrc);
    
    UIImage *drawImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    [self backgroundSettingWith:music image:drawImage];
}

- (void)backgroundSettingWith:(XMGMusic *)music image:(UIImage *)image{
    MPNowPlayingInfoCenter *infoCenter = [MPNowPlayingInfoCenter defaultCenter];
    NSMutableDictionary *playInfoDict = [NSMutableDictionary dictionary];
    [playInfoDict setObject:music.name forKey:MPMediaItemPropertyAlbumTitle];
    [playInfoDict setObject:music.singer forKey:MPMediaItemPropertyArtist];
    [playInfoDict setObject:@(self.time) forKeyedSubscript:MPMediaItemPropertyPlaybackDuration];
     MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
    [playInfoDict setObject:artwork forKey:MPMediaItemPropertyArtwork];
    infoCenter.nowPlayingInfo = playInfoDict;
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}


@end
